 ///
 /// @file    statistic.cc
 /// @author  lemon(haohb13@gmail.com)
 /// @date    2023-05-06 10:07:06
 ///
 
#include <map>
#include <string>
#include <sstream>
#include <fstream>
#include <iostream>
using std::cout;
using std::endl;
using std::map;
using std::string;
using std::ifstream;
using std::ofstream;
using std::istringstream;

class WordStatistic
{
public:
	WordStatistic() {}

	//在写代码时，一个函数不建议超过一屏(50行)
	void readFile(const string & name)
	{
		ifstream ifs(name);
		if(!ifs) {
			cout << "ifstream open file " << name << " error\n";
			return;
		}

		string line;
		while(getline(ifs, line)) {
			preprocessLine(line);//提取出函数
			istringstream iss(line);
			string word;
			while(iss >> word) {
				++_dict[word];
			}
		}

		ifs.close();
	}

	void store(const string & name)
	{
		ofstream ofs(name);
		if(!ofs) {
			cout << "ofstream open file " << name << " error" << endl;
			return;
		}
		for(auto & record : _dict) {
			ofs << record.first << " " << record.second << endl;
		}

		ofs.close();
	}
private:
	void preprocessLine(string & line)
	{
		for(auto & ch : line) {
			if(!isalpha(ch)) {
				ch = ' ';	
			} else if(isupper(ch)) {
				ch = tolower(ch);
			}
		}
	}

private:
	map<string, int> _dict;
};
 
void test0() 
{
	WordStatistic ws;
	clock_t start = clock();
	ws.readFile("The_Holy_Bible.txt");
	ws.store("dict.txt");
	clock_t end = clock();
	cout << "time:" << (end - start) << endl;
} 
 
int main(void)
{
	test0();
	return 0;
}
